//
//  PhotoViewerViewController.swift
//  PhotoBox
//
//  Created by 张明楠 on 14/12/23.
//  Copyright (c) 2014年 张明楠. All rights reserved.
//

import UIKit
import QuartzCore
import Alamofire
class PhotoViewerViewController: UIViewController,UIScrollViewDelegate ,UIActionSheetDelegate{

    var imageUrl:String?

    let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
    let scrollView = UIScrollView()
    let imageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpView()
        //加载图片
        loadPhoto()
    }

    func loadPhoto(){

        ImageLoader.sharedLoader.imageForUrl(imageUrl!, completionHandler: { (image, url) -> () in

            self.imageView.image = image
            self.imageView.frame = self.centerFrameFromImage(image)
            self.spinner.stopAnimating()
            self.centerScrollViewContents()

            //添加底部的工具条
            self.addButtomBar()

        })

    }

    func addButtomBar() {

        var items = [UIBarButtonItem]()
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
        items.append(flexibleSpace)
        items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: "showActions"))
        items.append(flexibleSpace)

        self.setToolbarItems(items, animated: true)
        navigationController?.setToolbarHidden(false, animated: true)

    }

    func showActions() {
        let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle:nil, otherButtonTitles: "收藏","下载")

        actionSheet.showFromToolbar(navigationController?.toolbar)
    }

    func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            downloadPhoto()
        }else if buttonIndex == 2 {

            UIImageWriteToSavedPhotosAlbum(self.imageView.image, self,"image:didFinishSavingWithError:contextInfo:",nil)
        }

    }
    // 保存到相册后的回调方法。
    func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo: UnsafePointer<()>){
        var alert = UIAlertView(title: "保存完成", message: nil, delegate: self, cancelButtonTitle: "确定")
        alert.show()
    }

    //下载图片
    func downloadPhoto(){
        var  destinationPath : (NSURL,NSHTTPURLResponse) -> (NSURL) = {
            (temporaryURL, response) in
            //返回下载文件的保存路径。
            if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
                return directoryURL.URLByAppendingPathComponent("\(response.suggestedFilename!)")
            }
            return temporaryURL
        }
        Alamofire.download(.GET, self.imageUrl!, destinationPath).progress {
            (_, totalBytesRead, totalBytesExpectedToRead) in
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                //更新进度条

            })
        }

    }


    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setToolbarHidden(true, animated: true)
    }


    //当图片比较小时， 将图片居中显示。
    func centerScrollViewContents() {
        let boundsSize = scrollView.frame
        var contentsFrame = self.imageView.frame

        if contentsFrame.size.width < boundsSize.width {
            contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0
        } else {
            contentsFrame.origin.x = 0.0
        }

        if contentsFrame.size.height < boundsSize.height {
            contentsFrame.origin.y = (boundsSize.height - scrollView.scrollIndicatorInsets.top - scrollView.scrollIndicatorInsets.bottom - contentsFrame.size.height) / 2.0
        } else {
            contentsFrame.origin.y = 0.0
        }

        self.imageView.frame = contentsFrame
    }

    //根据屏幕宽度设置 图片的宽高
    func centerFrameFromImage(image: UIImage?) -> CGRect {
        if image == nil {
            return CGRectZero
        }
        //根据 宽度比例 算出 高度的缩放比例
        let scaleFactor = scrollView.frame.size.width / image!.size.width
        let newHeight = image!.size.height * scaleFactor

        var newImageSize = CGSize(width: scrollView.frame.size.width, height: newHeight)

        //当高度超出屏幕 按照 屏幕实际高度作为 实际的高度。
        newImageSize.height = min(scrollView.frame.size.height, newImageSize.height)

        let centerFrame = CGRect(x: 0.0, y: scrollView.frame.size.height/2 - newImageSize.height/2, width: newImageSize.width, height: newImageSize.height)
        return centerFrame
    }
    
    func setUpView(){
        navigationController?.setNavigationBarHidden(false, animated: true)
        spinner.center = CGPoint(x: view.center.x, y: view.center.y - view.bounds.origin.y / 2.0)
        spinner.hidesWhenStopped = true
        spinner.startAnimating()
        self.view.addSubview(spinner)

        scrollView.frame = view.bounds
        scrollView.delegate = self
        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 3.0
        scrollView.zoomScale = 1.0
        self.view.addSubview(scrollView)

        imageView.contentMode = .ScaleAspectFill
        scrollView.addSubview(imageView)
        self.view.addSubview(scrollView)



        //添加双击手势
        let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "SELdoubleTap:")
        doubleTapRecognizer.numberOfTapsRequired = 2
        doubleTapRecognizer.numberOfTouchesRequired = 1
        scrollView.addGestureRecognizer(doubleTapRecognizer)


        let singleTapRecognizer = UITapGestureRecognizer(target: self, action: "SELsingleTap:")
        singleTapRecognizer.numberOfTapsRequired = 1
        singleTapRecognizer.numberOfTouchesRequired = 1
        singleTapRecognizer.requireGestureRecognizerToFail(doubleTapRecognizer)
        scrollView.addGestureRecognizer(singleTapRecognizer)

    }

    //隐藏或者显示导航条或者 工具条
    func SELsingleTap(ges:UITapGestureRecognizer!){
            let hidden = navigationController?.navigationBar.hidden ?? false
            navigationController?.setNavigationBarHidden(!hidden, animated: true)
            navigationController?.setToolbarHidden(!hidden, animated: true)
            UIApplication.sharedApplication().setStatusBarHidden(!hidden, withAnimation: .Slide)
    }

    func SELdoubleTap(ges:UITapGestureRecognizer!){

        let pointInView = ges.locationInView(self.imageView)

        //将点击的区域放大显示
        self.zoomInZoomOut(pointInView)
    }



    func zoomInZoomOut(point: CGPoint!) {
        let newZoomScale = self.scrollView.zoomScale > (self.scrollView.maximumZoomScale/2) ? self.scrollView.minimumZoomScale : self.scrollView.maximumZoomScale
        let scrollViewSize = self.scrollView.bounds.size
        let width = scrollViewSize.width / newZoomScale
        let height = scrollViewSize.height / newZoomScale
        let x = point.x - (width / 2.0)
        let y = point.y - (height / 2.0)
        var rectToZoom = CGRect(x: x, y: y, width: width, height: height)
        self.scrollView.zoomToRect(rectToZoom, animated: true)
    }
    func viewForZoomingInScrollView(scrollView: UIScrollView!) -> UIView! {
        return self.imageView
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
